<template>

  <!-- add -->
  <a-modal
    :mask-closable="false"
    :visible="addVisibleF"
    title="报文上传-管理上行地址"
    :footer="null"
    :class="['c-dialog-box c-dialog-box-nobg',singlePage?'c-dialog-box-full':'']"
    :width="1054"
    :z-index="modalZIndexM"
    :closable="!singlePage"
    centered
    @cancel="onClose"
  >
    <span slot="closeIcon" class="c-close-icon"><a-icon :component="require('@/assets/icon/close.svg')" /></span>
    <span v-if="!singlePage" class="new-page-btn" @click="goNewPageHandler"><a-icon :component="require('@/assets/icon/newPage.svg')" /></span>
    <a-spin :spinning="repUplinkDestinationLoading">
      <a-table
        class="glghs-table beauty-scroll"
        size="middle"
        :scroll="{ y: tableH }"
        :columns="columns"
        :data-source="[...repUplinkDestinationList,newData]"
        :row-selection="{
          selectedRowKeys:selectedRowKeys,
          onChange:onChangeRow
        }"
        :row-class-name="rowClassHandler"
        :pagination="false"
        :row-key="(row,index) =>index"
      />

      <!-- <vxe-table
        ref="xTable1"
        class="event-trigger-packet-upload mt-15 beauty-scroll"
        show-overflow
        highlight-hover-row
        row-id="id"
        :data="repUplinkDestinationList"
        :edit-config="{trigger: 'click', mode: 'cell'}"
      >
        <vxe-table-column field="name" title="供应商" width="140" :edit-render="{name: 'input'}" />
        <vxe-table-column field="title" title="描述" width="140" :edit-render="{name: 'input'}" />
        <vxe-table-column field="isBedo" title="Boding Edu Dynamic Override" :edit-render="{name: 'radio'}" />
        <vxe-table-column field="isIdo" title="Invalid Destination Override" :edit-render="{name: 'radio'}" />
        <vxe-table-column title="操作" width="140">
          <template #default="{ row }">
            <a-popconfirm
              title="确认删除此项?" ok-type="danger"
              ok-text="确认"
              cancel-text="取消"
              :get-popup-container="
                triggerNode => {
                  return triggerNode.parentNode || document.body;
                }
              "
              @confirm="delItemHandler(row)"
            >
                <a-button type="link" size="small" class="mr-5">删除</a-button>

              <a-button type="link" size="small" >

              </a-button>
          </template>
        </vxe-table-column> -->
      <div class="d-flex jc-between">
        <div class="lh-1 text-color-9ea5b2 fs-14 mt-18">
          添加 "动态 "作为目的地，将使AHM选择我们最近收到的信息的IATA地址作为目的地。<br>
          如果你希望有这种功能，请添加它。
        </div>
        <div>
          <a-button class="mt-16 mr-12" type="primary" :disabled="addBtnDis" ghost @click="addHandler">添加</a-button>
          <a-button class="mt-16 mr-12" type="primary" :disabled="updateBtnDis" ghost @click="updateHandler">更新</a-button>
          <a-button class="mt-16" type="primary" :disabled="delBtnDis" ghost @click="delHandler">删除</a-button>
        </div>
      </div>
    </a-spin>

  </a-modal>

  <!-- add
  <a-moda
    :maskClosable="false"
    v-model="addItemVisible"
    :title="`${addTitle}分组`"
    :confirm-loading="addRepUplinkDestinationLoading"
    @ok="addConfirmHandler"
    @cancel="cancelHandler"
  >

    <a-form-model
      ref="addForm"
      :model="addForm"
      :rules="addRules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-form-model-item label="报文目的地名称" prop="name">
        <a-input v-model="addForm.name" style="width: 100%" />
      </a-form-model-item>
      <a-form-model-item label="地址组描述" prop="title">
        <a-input v-model="addForm.title" style="width: 100%" />
      </a-form-model-item>
      <a-form-model-item label="isIdo" prop="isIdo">
        <a-input v-model="addForm.isIdo" style="width: 100%" />
      </a-form-model-item>
      <a-form-model-item label="isBedo" prop="isBedo">
        <a-input v-model="addForm.isBedo" style="width: 100%" />
      </a-form-model-item>
    </a-form-model>
  </a-modal> -->
</template>

<script>
import { mapState, mapActions, mapMutations } from 'vuex';
export default {
  props: {
    addVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      modalZIndexM: 2000,
      tableH: 237,
      selectedRowKeys: [],
      selectedRowData: [],
      addBtnDis: true,
      updateBtnDis: true,
      delBtnDis: true,
      newData: { add: true },
      columns: [
        {
          title: '上行地址',
          align: 'left',
          dataIndex: 'name',
          width: 180,
          customRender: (value, record, index) => {
            if (record.add) {
              return <a-input placeholder='' class='input-type-o' value={this.newData.name} onInput={(e) => this.addDataHandler(e, 'name')} />;
            } else {
              return <a-input placeholder='' class='input-type-o' value={record['name']} onInput={(e) => this.uDataHandler(e, 'name', index)} />;
            }
          }
        },
        {
          title: '描述',
          align: 'left',
          dataIndex: 'title',
          customRender: (value, record, index) => {
            if (record.add) {
              return <a-input placeholder='' class='input-type-o' value={this.newData.title} onInput={(e) => this.addDataHandler(e, 'title')} />;
            } else {
              return <a-input placeholder='' class='input-type-o' value={record['title']} onInput={(e) => this.uDataHandler(e, 'title', index)} />;
            }
          }

        },
        {
          title: '动态改写',
          align: 'left',
          dataIndex: 'isBedo',
          width: 210,
          customRender: (value, record, index) => {
            return <a-radio checked={value === 1} onClick={(e) => this.changeRadio(value, index, 'isBedo')}></a-radio>;
          }

        },
        {
          title: '报错覆盖',
          align: 'left',
          dataIndex: 'isIdo',
          width: 200,
          customRender: (value, record, index) => {
            return <a-radio checked={value === 1} onClick={(e) => this.changeRadio(value, index, 'isIdo')}></a-radio>;
          }

        }
      ]
    };
  },
  computed: {
    ...mapState('fraMonitoring', [
      'repUplinkDestinationList',
      'repUplinkDestinationLoading',
      'addRepUplinkDestinationLoading',
      'modalZIndex'
    ]),
    addVisibleF() {
      return this.addVisible || this.$route.query.full === '1';
    },
    singlePage() {
      return ((this.$route.meta?.singlePage ?? false) && this.$route.query.full === '1');
    }
  },

  watch: {

    'addVisibleF': {
      async handler(nv) {
        if (nv) {
          this.setState({ key: 'modalZIndex', payload: this.modalZIndex + 1 });
          this.modalZIndexM = this.modalZIndex;
          this.newData = { add: true };
          this.selectedRowKeys = [];
          this.selectedRowData = [];
          await this.getRepUplinkDestination();
          this.$nextTick(() => {
            setTimeout(() => {
              this.tableH = this.singlePage ? document.body.clientHeight - 178 : 237;
              document.querySelector('.glghs-table .ant-table-body').scrollTop = 20000;
            }, 300);
          });
        } else {
          if (!this.singlePage) {
            this.getUploadMessageConditionsPri();
          }
        }
      },
      immediate: true
    }
  },
  methods: {
    ...mapActions('fraMonitoring', [
      'getRepUplinkDestination',
      'getUploadMessageConditionsPri',
      'addRepUplinkDestination',
      'updateRepUplinkDestination',
      'deleteRepUplinkDestination'
    ]),
    ...mapMutations('fraMonitoring', [
      'setState'
    ]),
    // 新增
    addHandler() {
      if (this.newData.name && this.newData.title) {
        this.addRepUplinkDestination(this.newData).then((rep) => {
          if (rep) {
            this.newData = { add: true };
            this.getRepUplinkDestination();
            this.selectedRowKeys = [this.selectedRowKeys[0] + 1];
            this.selectedRowData = [];
            document.querySelector('.glghs-table .ant-table-body').scrollTop += 200;
          }
        });
      }
    },
    // 批量更改
    updateHandler() {
      let f = false;
      for (const iterator of this.repUplinkDestinationList) {
        if (iterator.name === '' || iterator.title === '') {
          f = true;
        }
      }
      if (!f) {
        this.updateRepUplinkDestination(this.selectedRowData);
      } else {
        this.$message.error('供应商和描述不能为空');
      }
    },
    // 批量删除
    delHandler() {
      const ids = this.selectedRowData.flatMap(item => item.id);
      this.deleteRepUplinkDestination(ids).then((rep) => {
        if (rep) {
          this.getRepUplinkDestination();
          this.selectedRowKeys = [this.selectedRowKeys[0] + 1];
          this.selectedRowKeys = [];
          this.selectedRowData = [];
        }
      });
    },
    addDataHandler(e, key) {
      this.$set(this.newData, key, e.target.value);
    },
    uDataHandler(e, key, index) {
      this.repUplinkDestinationList[index][key] = e.target.value;
    },
    rowClassHandler(record, index) {
      let className = ['dark-t-row'];
      if (index % 2 === 1) className = ['light-t-row'];

      return className;
    },
    onChangeRow(selectedRowKeys, selectedAll) {
      this.addBtnDis = true;
      this.updateBtnDis = true;
      this.delBtnDis = true;
      let na = [...selectedRowKeys].sort((a, b) => a - b);

      const addIndex = na.findIndex(item => item === this.repUplinkDestinationList.length);
      const addIndex2 = selectedRowKeys.findIndex(item => item === this.repUplinkDestinationList.length);
      if (this.repUplinkDestinationList.length !== 0) {
        if (na.length === this.repUplinkDestinationList.length + 1) {
          if (na.length - 1 === this.selectedRowKeys.length && na[na.length - 1] === this.repUplinkDestinationList.length) {
            na = [];
          } else {
            na.splice(addIndex, 1);
          }
        } else if (addIndex2 === 0) {
          if (selectedRowKeys.length > 1) {
            selectedRowKeys.shift();
          }
          na = selectedRowKeys;
        } else if (addIndex2 > 0) {
          na = [this.repUplinkDestinationList.length];
        }

        if (na.length === 1 && na[0] === this.repUplinkDestinationList.length) {
          this.addBtnDis = false;
          selectedAll = [this.newData];
        } else {
          if (na.length === 0) {
            this.updateBtnDis = true;
            this.delBtnDis = true;
          } else {
            this.updateBtnDis = false;
            this.delBtnDis = false;
          }
        }
        if (selectedAll.length > 1 && selectedAll[selectedAll.length - 1].add) {
          selectedAll.pop();
        }
      } else {
        if (na.length === 1 && na[0] === this.repUplinkDestinationList.length) {
          this.addBtnDis = false;
        }
      }
      this.selectedRowKeys = na;
      this.selectedRowData = selectedAll;
      // console.log(record, selected, selectedRows);
    },
    changeRadio(value, index, key) {
      const flag = !value ? 1 : 0;

      if (index === this.repUplinkDestinationList.length) {
        this.$set(this.newData, key, flag);
      } else {
        this.repUplinkDestinationList[index][key] = flag;
      }
    },

    // 当drawer点击关闭
    onClose() {
      this.$emit('close', false);
    },
    goNewPageHandler() {
      const routeData = this.$router.resolve({
        path: 'messageUploadGls',
        query: {
          full: '1'
        }
      });

      window.open(routeData.href, '_blank');
    }
  }
};
</script>

<style lang="less">
@import "../../index.less";
.glghs-table{

border: 1px solid #EBECEF;
border-bottom: none;
th,td{
  padding: 11px 8px!important;
}
.ant-table-row-cell-break-word{
  padding-top:0!important;
  padding-bottom:0!important;

}
  .ant-input{
  background-color: #FFFFFF!important;
    border:1px solid #D4D9E2!important;
        margin: -10px auto;
  }

}
.c-dialog-box-nobg{
  .new-page-btn{
     top: -27px!important;
       path{
        fill:#9EA5B2
      }

}
    .ant-modal-close-x{

      path{
        fill:#9EA5B2
      }
        .c-close-icon {

    &:hover {
      background-color: #fff;
    }
  }
  }
}
</style>
